package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-02-20
 * Time: 15:45
 */
public class DelOperation implements IOperation {

    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书");

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要删除的书的书名");
        String name = scanner.nextLine();
        int index = -1;

        int currenSize = bookList.getUsedSize(); //得到书架的图书数量
        int i = 0;
        for (; i < currenSize; i++) {
            Book book = bookList.getBook(i);
            if (book.getName().equals(name)) {
                index = i;
                break;  //记录下来要删除图书的姓名
            }
        }
        if(i >= currenSize) {
            System.out.println("没有你要删除的图书!");
            return;
        }

        //删除的逻辑是移动后面的数据进行覆盖,最好size--

        for (int j = index; j < currenSize-1; j++) {
            Book book = bookList.getBook(j+1);
            bookList.setBook(book,j);
        }

        bookList.setBook(null,currenSize-1);  //最后一位置为空
        bookList.setUsedSize(currenSize-1);
        System.out.println("删除成功!");
    }
}
